package com.free.space.controller.tool;

import com.alibaba.fastjson.JSONObject;
import com.free.space.common.CommonGetParameter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import sun.net.www.protocol.http.HttpURLConnection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * http 请求并发测试
 * Created by zhulj on 2019/3/26.
 */
@Controller
public class ConcurrentHttpController extends CommonGetParameter {
    /**
     * http 请求参数
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("concurrentHttpTest")
    public void concurrentHttpTest(HttpServletRequest request, HttpServletResponse response) throws Exception{
        JSONObject json  = getParameter(request);
    //    json = JSONObject.parseObject("{url:http://127.0.0.1:8080/hospital/index/review,cookie:JSESSIONID=8cb5843f5492fa3260e354498f6e,coreSize:5,thSize:10000,content:\"{test: 1}\"}");
        connectionHttpStar(json);
    }
    public void connectionHttpStar(JSONObject json){
        String url = json.getString("url");
        String cookie = json.getString("cookie");
        int coreSize = json.getInteger("coreSize");
        int thSize = json.getInteger("thSize");
        String content = json.getString("content");

        ThreadPoolExecutor threadExecutor = new ThreadPoolExecutor(coreSize, coreSize, 1, TimeUnit.SECONDS, new LinkedBlockingDeque<>(20048), new MyThreadFactory());
        threadExecutor.allowCoreThreadTimeOut(true);
        for (int i = 0; i < thSize; i++) {
            MyThread myThread = new MyThread(url,cookie,content);
            Thread thread = new Thread(myThread);
            threadExecutor.execute(myThread);
        }
        while (true) {
            try {
                Thread.sleep(1000);
                System.out.println(threadExecutor.getCompletedTaskCount());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (null == threadExecutor || threadExecutor.getActiveCount() <= 0) {
                break;
            }
        }
    }
    public void connectionHttp(String urlStr,String cookie,String content) {
        try {
            //请求的webservice的url
            URL url = new URL(urlStr);
            //创建http链接
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            //设置请求的方法类型
            httpURLConnection.setRequestMethod("GET");
            //设置请求的内容类型
            httpURLConnection.setRequestProperty("Content-type", "application/json");
            httpURLConnection.setRequestProperty("Cookie", "JSESSIONID=8cb5843f5492fa3260e354498f6e");
            ;
            //设置发送数据
            httpURLConnection.setDoOutput(true);
            //设置接受数据
            httpURLConnection.setDoInput(true);
            //发送数据,使用输出流
            OutputStream outputStream = httpURLConnection.getOutputStream();
            //发送的soap协议的数据
            //String content =  URLEncoder.encode("{test: 1}", "utf-8");

            //发送数据
            outputStream.write(content.getBytes());
            //接收数据
            InputStream inputStream = httpURLConnection.getInputStream();
            //  printResponseData(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 打印返回结果
     *
     * @param inputStream
     */
    private static void printResponseData(InputStream inputStream) throws Exception {
        //定义字节数组
        byte[] b = new byte[1024];

        //定义一个输出流存储接收到的数据
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        //开始接收数据
        int len = 0;
        while (true) {
            len = inputStream.read(b);
            if (len == -1) {
                //数据读完
                break;
            }
            byteArrayOutputStream.write(b, 0, len);
        }

        //从输出流中获取读取到数据(服务端返回的)
        String response = byteArrayOutputStream.toString();

        System.out.println(response);
    }
    class MyThread implements Runnable {
        String urlStr;
        String cookie;
        String content;
        MyThread(String urlStr,
                String cookie,
                String content){
            this.urlStr =urlStr;
            this.cookie =cookie;
            this.content =content;
        }
        @Override
        public void run() {
            connectionHttp(urlStr,cookie,content);
        }
    }
}



/**
 * 临时表数据保存到业务表线程工厂
 */
class MyThreadFactory implements ThreadFactory {
    @Override
    public Thread newThread(Runnable r) {
        return new Thread(r, "线程名称-" + System.currentTimeMillis());
    }
}
